<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

// 读取用户数据
$userDataDir = 'data/users.json';
$userData = json_decode(file_get_contents($userDataDir, true);

// 接收 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理注册
    if (isset($_POST['username']) && isset($_POST['password'])) {
        $username = $_POST['username'];
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);

        // 检查用户名是否已存在
        if (!usernameExists($userData, $username)) {
            // 添加新用户
            $newUser = array('username' => $username, 'password' => $password);
            $userData['users'][] = $newUser;

            // 更新用户数据文件
            file_put_contents($userDataDir, json_encode($userData));

            echo json_encode(array('status' => 200, 'message' => 'Registration successful.'));
        } else {
            echo json_encode(array('status' => 500, 'message' => 'Username already exists.'));
        }
    } else {
        echo json_encode(array('status' => 500, 'message' => 'Invalid data.'));
    }
}

// 检查用户名是否已存在
function usernameExists($userData, $username)
{
    foreach ($userData['users'] as $user) {
        if ($user['username'] === $username) {
            return true;
        }
    }
    return false;
}
?>